package com.nuo.gateway.log;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.nuo.common.core.constant.TraceLogConstants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 添加全局TraceID 到mdc和header
 *
 * @author LGC
 */
@Slf4j
@Component
public class TraceLogGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = exchange.getRequest().getHeaders().getFirst(TraceLogConstants.TRACE_ID_HEADER);
        if (StrUtil.isBlank(traceId)) {
            traceId = IdUtil.fastSimpleUUID();
        }
        //日志id放入MDC当前线程副本中
        MDC.put(TraceLogConstants.TRACE_ID, traceId);
        String finalTraceId = traceId;
        ServerHttpRequest request = exchange.getRequest().mutate().headers(h -> h.add(TraceLogConstants.TRACE_ID_HEADER, finalTraceId)).build();
        ServerWebExchange build = exchange.mutate().request(request).build();
        log.info("Create traceId to MDC and Set into Header");
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return 1;
    }

}